package com.hitsz.cdq;

import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;


/**
 * Created by ChenDongqiang on 2017/3/1.
 */
public class RemoteControlFragment extends Fragment {

    private Button btn_forward, btn_back, btn_left, btn_right;

    private Button btn_connect;
    private EditText receive_data, tv_port, ip_address, send_data;
    private TextView tv_client_state;

    private InputStream inputStream;//创建输入数据流
    private OutputStream outputStream;//创建输出数据流

    private ClientSocket_thread mClientSocket_thread;
    private Receive_Thread mReceive_Thread;
    private Socket clientSocket;
    private Boolean isConnected, isClientSocket_threadWorking, isReceive_ThreadWorking;
    public static String data_tcp_client;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_remote_control, container, false);
        btn_forward = (Button) view.findViewById(R.id.btn_forward);
        btn_forward.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    try {
                        outputStream.write("f".getBytes());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    try {
                        outputStream.write("s".getBytes());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });
        btn_back = (Button) view.findViewById(R.id.btn_back);
        btn_back.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    try {
                        outputStream.write("b".getBytes());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    try {
                        outputStream.write("s".getBytes());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });
        btn_left = (Button) view.findViewById(R.id.btn_left);
        btn_left.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    try {
                        outputStream.write("l".getBytes());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    try {
                        outputStream.write("s".getBytes());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });
        btn_right = (Button) view.findViewById(R.id.btn_right);
        btn_right.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    try {
                        outputStream.write("r".getBytes());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    try {
                        outputStream.write("s".getBytes());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });

        receive_data = (EditText) view.findViewById(R.id.receive_data);
        receive_data.setFocusable(false);
        tv_port = (EditText) view.findViewById(R.id.tv_port);
        ip_address = (EditText) view.findViewById(R.id.ip_address);
        send_data = (EditText) view.findViewById(R.id.send_data);
        tv_client_state = (TextView) view.findViewById(R.id.tv_client_state);

        btn_connect = (Button) view.findViewById(R.id.btn_connect);
        isConnected = false;
        tv_client_state.setText("未连接");
        btn_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isConnected) {
                    stopClient();
                    btn_connect.setText("连接");
                } else {
                    startClient();
                    btn_connect.setText("断开");
                }
            }
        });

        return view;
    }

    private void startClient() {
        isClientSocket_threadWorking = true;
        if (mClientSocket_thread == null) {
            mClientSocket_thread = new ClientSocket_thread();
            mClientSocket_thread.start();
        }

        isReceive_ThreadWorking = true;
        if (mReceive_Thread == null) {
            mReceive_Thread = new Receive_Thread();
            mReceive_Thread.start();
        }

        isConnected = true;
        tv_client_state.setText("连接成功");
        tv_client_state.setTextColor(Color.GREEN);
    }

    private void stopClient() {
        isClientSocket_threadWorking = false;
        isReceive_ThreadWorking = false;
        mClientSocket_thread.interrupt();
        mClientSocket_thread = null;
        mReceive_Thread.interrupt();
        mReceive_Thread = null;
        isConnected = false;
        tv_client_state.setText("连接已断开");
        tv_client_state.setTextColor(Color.RED);
    }


    /**
     * 客户端线程
     */
    class ClientSocket_thread extends Thread {
        public void run()//重写Thread的run方法
        {
            try {
                clientSocket = new Socket(ip_address.getText().toString(), Integer.valueOf(tv_port.getText().toString()));
                inputStream = clientSocket.getInputStream();
                outputStream = clientSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (!isClientSocket_threadWorking) {
                try {
                    if (inputStream != null && outputStream != null) {
                        inputStream.close();
                        outputStream.close();
                        clientSocket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }

    }

    class Receive_Thread extends Thread//继承Thread
    {
        public void run()//重写run方法
        {
            while (isReceive_ThreadWorking) {
                try {
                    final byte[] buf = new byte[1024];
                    final int len = inputStream.read(buf);
                    if (len == -1) {
                        break;
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            try {
                                data_tcp_client = new String(buf, 0, len, "gb2312");
                                receive_data.getText().append(new String(buf, 0, len, "gb2312"));
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            receive_data.getText().append("\n");
                        }
                    });
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }


}
